<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 用户 -->
      <el-form-item label="用户" prop="userId">
        <el-select
          v-model="queryParams.userId"
          placeholder="请输入用户的真实姓名"
          clearable
          @keyup.enter="handleQuery"
        style="width: 150px;">
        <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id"/>
        </el-select>
      </el-form-item>
       <!-- 商户 -->
      <el-form-item label="商户" prop="merchantId">
        <el-select
          v-model="queryParams.merchantId"
          placeholder="请输入商户"
          clearable
          @keyup.enter="handleQuery"
        style="width: 150px;">
        <el-option v-for="item in MerchantInfo" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 150px;">
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" 
          />
        </el-select>
      </el-form-item>
      <!-- 优惠劵 -->
      <el-form-item label="优惠劵" prop="serviceId">
        <el-select v-model="queryParams.serviceId" placeholder="请选择优惠劵" clearable @keyup="handleQuery" style="width: 170px;">
          <el-option
            v-for="dict in couponList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" prop="reservationTime">
        <el-date-picker clearable
          v-model="queryParams.reservationTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable
          v-model="queryParams.orderTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['offer:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['offer:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['offer:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['offer:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" width="50" /> -->
       <el-table-column label="订单编号" align="center" prop="orderNum" width="150" />
      <el-table-column label="用户" align="center" prop="userId">
        <template #default="scope">
       <span> {{userList?.find(item => item.id === scope.row.userId)?.nickName || '未知用户'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="商家名" align="center" prop="merchantId">
        <template #default="scope">
       <span> {{MerchantInfo?.find(item => item.id === scope.row.merchantId)?.name || '未知商家'}}</span>
        </template>
        </el-table-column>
      <el-table-column label="服务名称" align="center" prop="serviceId" width="100px">
          <template #default="scope">
          {{ServiceInfo?.find(item => item.id === scope.row.serviceId)?.serviceName || '未知服务'}}
          </template>
        </el-table-column>
      <el-table-column label="订单价格" align="center" prop="orderPrice" />
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="reservationTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reservationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="核销码" align="center" prop="verificationCode">
        <template #default="scope">
          <el-button link type="primary" @click="showCodeDialog(scope.row.verificationCode)">
            查看核酸码
          </el-button>
        </template>
        </el-table-column>
      <el-table-column label="核销码图片" width="100" align="center" prop="verificationImg">
        <template #default="scope">
          <image-preview :src="scope.row.verificationImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="车辆信息" align="center" width="80">
  <template #default="scope">
    <el-popover placement="right" :width="380" trigger="hover">
      <template #reference>
        <el-button link type="primary">查看车辆</el-button>
      </template>
      <div class="car-info-container">
        <div 
          v-for="car in carInfoList.filter(c => c.uid === scope.row.userId)" 
          :key="car.id"
          class="car-item">
          <el-icon class="car-icon"><user /></el-icon>
          <div class="car-details">
            <div class="car-brand-type">
              <!-- 修改品牌显示为品牌名称 -->
              <span class="brand">
                {{ brandList.find(b => b.id === car.brand)?.name || '未知品牌' }}
              </span>
              <el-divider direction="vertical" />
              <!-- 修改类型显示为类型名称 -->
              <span class="type">
                {{ typeList.find(t => t.id === car.type)?.name || '未知类型' }}
              </span>
            </div>
            <!-- 保持车牌号显示 -->
            <div class="car-number">
              <el-tag type="info" size="small">{{ car.carNum }}</el-tag>
            </div>
          </div>
        </div>
      </div>
    </el-popover>
  </template>
</el-table-column>
      <el-table-column label="优惠劵" align="center" prop="couponId">
        <template #default="scope">
          <span>{{couponList.find(item=>item.id===scope.row.couponId)?.name || '未知'}}</span>
        </template>
        </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['offer:orders:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['offer:orders:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请输入用户" @change="handleUserChange">
            <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id"/>
            </el-select>
        </el-form-item>
        <el-form-item label="商户" prop="merchantId">
          <el-select v-model="form.merchantId" placeholder="请输入商户" clearable>
         <el-option v-for="item in MerchantInfo" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
        </el-form-item>
        <el-form-item label="服务" prop="serviceId">
          <el-select v-model="form.serviceId" placeholder="请输入服务名称" clearable>
            <el-option v-for="item in ServiceInfo" :key="item.id" :label="item.serviceName" :value="item.id"/>
            </el-select>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="系统自动生成" :readonly="true" disabled style="width: 100%;" />
        </el-form-item>
        <el-form-item label="订单价格" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单价格" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-radio-group v-model="form.orderStatus">
            <el-radio
              v-for="dict in order_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预约时间" prop="reservationTime">
          <el-date-picker clearable
            v-model="form.reservationTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="核销码" prop="verificationCode">
  <el-input 
    v-model="form.verificationCode" 
    placeholder="系统自动生成" 
    :readonly="true" 
    disabled
  />
  <el-button 
  v-if="!form.id && !form.verificationCode" 
  type="primary" 
  @click="generateOrderNum"
  style="margin-left: 10px;"
>生成二维码</el-button>
</el-form-item>
<el-form-item label="核销码图" width="100" prop="verificationImg">
  <image-upload 
    v-model="form.verificationImg" 
    :disabled="!!form.id" 
  />
</el-form-item>
        <el-form-item label="关联车辆" prop="carId">
            <div class="car-list-container">
              <div 
                v-for="car in filteredCarList" 
                :key="car.id"
                class="car-item"
                :class="{ 'selected': form.carId === car.id }"
                @click="form.carId = car.id">
                <div class="car-info">
                  <span class="brand">{{ brandList.find(b => b.id === car.brand)?.name || '未知品牌' }}</span>
                  <el-divider direction="vertical" />
                  <span class="type">{{ typeList.find(t => t.id === car.type)?.name || '未知类型' }}</span>
                  <el-tag type="info" size="small" class="car-number">{{ car.carNum }}</el-tag>
                </div>
              </div>
              <div v-if="filteredCarList.length === 0" class="no-car">该用户暂无车辆信息</div>
            </div>
          </el-form-item>
        <el-form-item label="优惠卷" prop="couponId">
            <el-select v-model="form.couponId" placeholder="请选择优惠卷" clearable>
              <el-option v-for="item in couponList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
        </el-form-item>
        <el-form-item label="删除状态" prop="del">
          <el-input v-model="form.del" placeholder="请输入删除状态" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看核酸码对话框 -->
     <el-dialog v-model="dialogVisible" title="核算验证码详情" width="30%">
      <span class="verification-code">{{currentVerificationCode}}</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
     </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/offer/orders"
import { listMerchant} from "@/api/merchant/merchant"
import { listDetails} from "@/api/evaluate/details"
import {listInfo} from "@/api/bigbase/info"
import { listCoupon} from "@/api/xsc/coupon"
import {v4 as uuidv4, validate} from 'uuid'
import { listCarInfo } from "@/api/bigbase/carInfo"
import { listBrand } from "@/api/bigbase/brand"
import { listType } from "@/api/bigbase/type"
import QRCode from 'qrcode'
const { proxy } = getCurrentInstance()
const { order_status } = proxy.useDict('order_status')

const ordersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const MerchantInfo=ref([]);
const ServiceInfo=ref([]);
const userList=ref([]);
const couponList=ref([]);
const carInfoList=ref([])
const brandList = ref([])
const typeList = ref([])
// 查看核酸码对话框
const dialogVisible=ref(false);
const currentVerificationCode=ref("");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantId: null,
    serviceId: null,
    orderNum: null,
    userId: null,
    orderPrice: null,
    orderStatus: null,
    reservationTime: null,
    orderTime: null,
    verificationCode: null,
    verificationImg: null,
    couponId: null,
    del: null
  },
  rules: {
    reservationTime:[
      {
      validate: (rule,value,callback)=>{
        if(!value || !form.value.orderTime){
          return callback()
        }
        if(new Date(value)<=new Date(form.value.orderTime)){
          callback(new Error("预约时间必须晚于下单时间"));
        }else{
          callback()
        }
      },
      trigger: 'change'
    }
    ],
    orderTime:[
      {
        validate:(rule,value,callback)=>{
          if(!value ||!form.value.reservationTime){
            return callback()
          } 
          if(new Date(value)>=new Date(form.value.reservationTime)){
            callback(new Error("下单时间必须早于预约时间"));
          }else{
            callback()
          }
        },
        trigger: 'change'
      }
    ],

  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询订单表列表 */
function getList() {
  loading.value = true
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
//获取商户列表
function getMerchant(){
  loading.value = true
  listMerchant(queryParams.value).then(response => {
    MerchantInfo.value=response.rows;
    loading.value = false//请求完成后关闭加载状态
  }).catch(error=>{
    console.error("获取数据失败",error);
    loading.value = false;//请求失败也关闭加载状态
  })
}
//获取服务列表
function getService(){
  loading.value = true
  listDetails(queryParams.value).then(response => {
    ServiceInfo.value=response.rows;
    loading.value = false//请求完成后关闭加载状态  
  }).catch(error=>{
    console.error("获取数据失败",error);
    loading.value = false;//请求失败也关闭加载状态
  })
}
//获取用户列表
function getUserList() {
  listInfo({ pageNum: 1, pageSize: 10000 }).then(response => {
    userList.value = response.rows
    getCarInfoForAllUsers(response.rows.map(user => user.id))
  })
}
// 添加用户选择变更处理函数
function handleUserChange(userId) {
  // 清空已选车辆
  form.value.carId = null
  // 重新获取车辆信息
  getCarInfoForAllUsers([userId])
}
const filteredCarList = computed(() => {
  return carInfoList.value.filter(c => c.uid === form.value.userId)
})
// 获取车辆信息
function getCarInfoForAllUsers(userIds) {
  listCarInfo({ uids: userIds.join(',') }).then(response => {
    carInfoList.value = response.rows
  })
}
function getBrandList() {
  listBrand().then(response => {
    brandList.value = response.rows
  })
}

function getTypeList() {
  listType().then(response => {
    typeList.value = response.rows
  })
}
//生成订单编号
// 修改生成订单编号函数
function generateOrderNum(){
  if (!form.value.verificationCode) {
    const now = new Date();
    const timePart = now.toISOString().replace(/[-:T.]/g,'').slice(2, 16);
    const randomPart = Math.floor(Math.random()*10000).toString().padStart(4, '0');
    form.value.orderNum = `ORD${timePart}${randomPart}`;
    form.value.verificationCode = uuidv4();
  }
  }
//获取优惠卷列表
function getCoupon(){
  loading.value = true
  listCoupon(queryParams.value).then(response => {
   couponList.value=response.rows;
    loading.value = false//请求完成后关闭加载状态 
  }).catch(error=>{
    console.error("获取数据失败",error);
    loading.value = false;//请求失败也关闭加载状态
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    merchantId: null,
    serviceId: null,
    orderNum: null,
    userId: null,
    orderPrice: null,
    orderStatus: null,
    reservationTime: null,
    orderTime: null,
    verificationCode: null,
    verificationImg: null,
    couponId: null,
    del: null
  }
  proxy.resetForm("ordersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  generateOrderNum()
  setTimeout(()=>{
    open.value = true
  title.value = "添加订单表"
  },300)
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = response.data
    // 保留已有二维码或生成新二维码
    if(!form.value.verificationImg || !form.value.verificationCode) {
      form.value.verificationCode = uuidv4();  // 保证验证码存在
    }
    setTimeout(() => {
      open.value = true
      title.value = "修改订单表"
    }, 100)
  })
}

/** 提交按钮 */
async function submitForm() {
  proxy.$refs["ordersRef"].validate(async valid => {
    if (valid) {
      try {
        // 确保先生成二维码再提交
        if(!form.value.verificationImg) {
          await generateQRCode(form.value.verificationCode);
        }
        
        // ... 保持原有提交逻辑 ...
      } catch (error) {
        proxy.$modal.msgError("操作失败，请检查控制台");
        console.error("提交错误:", error);
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单表编号为"' + _ids + '"的数据项？').then(function() {
    return delOrders(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('offer/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}
// 查看核酸码
function showCodeDialog(code) {
  currentVerificationCode.value = code;
  dialogVisible.value = true;
}
getList()
getMerchant()
getService()
getUserList()
getCoupon()
getBrandList()
getTypeList()

</script>
<style scoped>
.verification-code {
  font-size: 24px;
  letter-spacing: 2px;
  text-align: center;
  display: block;
  font-family: monospace;
}
.car-info-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 8px 0;
}

.car-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin: 4px 0;
  background: #f8f9fa;
  border-radius: 4px;
  transition: background 0.2s;
}

.car-item:hover {
  background: #e9ecef;
}

.car-icon {
  font-size: 20px;
  margin-right: 12px;
  color: #409eff;
}

.car-details {
  flex-grow: 1;
}

.car-brand-type {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.brand {
  font-weight: 600;
  color: #343a40;
}

.type {
  color: #6c757d;
}

.car-number :deep(.el-tag) {
  font-family: monospace;
  letter-spacing: 1px;
}
.qr-placeholder {
  color: #999;
  font-size: 14px;
  padding: 20px;
  border: 1px dashed #ddd;
  text-align: center;
}
.car-list-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
}
.car-item {
  padding: 8px;
  margin: 4px 0;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
}

.car-item:hover {
  background-color: #f5f7fa;
}

.car-item.selected {
  background-color: #ecf5ff;
  border: 1px solid #409eff;
}


.car-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.no-car {
  color: #909399;
  text-align: center;
  padding: 12px;
}
</style>
